#include "../Code_309/Iom/IO_Cim_Data.h"
#include "../Code_309/Mfk/Mfk.h"

#include "Device_MFK.h"

#define kNumOfMFKDevices	2
#define kMaxNumOfMFKInputChars	16


typedef struct {
	bool valid;
	SFScreenId screenId;
	MFKInputEnded endCallback;
	char inputString[kMaxNumOfMFKInputChars];
}MFKHandle;

static MFKHandle m_handles[kNumOfMFKDevices] = {
	{.valid = FALSE,},
	{.valid = FALSE,},
};


extern SFCode MFKStartInput(SFScreenId screenId, const char *message, MFKInputEnded endCallback){
	MFKHandle *handle = &m_handles[screenId/2];
	
	if((handle->valid)&&((handle->endCallback)!=NULL)){
		handle->endCallback(handle->screenId);
	}
	handle->valid = TRUE;
	handle->screenId = screenId;
	handle->endCallback = endCallback;
	
	/* TODO: manipulate with the MFK */

	return SFCodeOK;
}

extern SFCode MFKEndInput(SFScreenId screenId){
	MFKHandle *handle = &m_handles[screenId/2];
	
	if((handle->screenId) == screenId){
		handle->valid = FALSE;
	}

	return SFCodeOK;
}

extern SFCode MFKReadInputString(SFScreenId screenId, const char **cString, SFInputStringMode *mode){
	int deviceId = screenId/2;
	MFKHandle *handle = &(m_handles[deviceId]);
	char *data = &(Cim_Mfk_R_Data[deviceId][0]);

	if(!(handle->valid)){
		return SFCodeNoData;
	}	
		
	if(data[0] == MFK_LED_DISP){
		char strLen = data[1];
		*cString = &data[2];
		*mode = SFInputStringModeNone;
		if(data[2+strLen-1] == K_MFK_SHF){
			*mode |= SFInputStringModeMaskPinyin;
			data[2+strLen-1] = '\0';
		}
	}else if((data[0] == MFK_KEY) && (data[2] == K_MFK_ENT)){
		*cString = "\n";
		*mode = SFInputStringModeNone;
	}else{
		return SFCodeNoData;
	}
	
	/* clear */
	data[0] = 0;
	data[1] = 0;
	
	return SFCodeOK;
}

